package com.levi.utils.log.formatter;


import androidx.annotation.Nullable;

/**
 * Created by Levi on 2018/3/13.
 */
public class MethodInfoDecorator extends Decorator {

    private final String mUtilClassName;

    public MethodInfoDecorator(Class<?> utilClassName) {
        mUtilClassName = utilClassName.getName();
    }

    @Nullable
    @Override
    public String decorate(@Nullable String msg) {
        final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        final int stackOffset = getStackOffset(trace);
        if (stackOffset < 0) {
            return msg;
        }
        return "\n" + trace[stackOffset].toString() + "\n" + msg;
    }

    @SuppressWarnings("PMD.UseVarargs")
    private int getStackOffset(StackTraceElement[] trace) {
        boolean findLoggerClass = false;
        for (int i = 0; i < trace.length; i++) {
            if (mUtilClassName.endsWith(trace[i].getClassName())) {
                findLoggerClass = true;
            } else if (findLoggerClass) {
                return i;
            }
        }
        return -1;
    }
}
